package com.citybiz.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.citybiz.common.config.TencentCosConfig;
import com.citybiz.common.exception.ServiceException;
import com.citybiz.common.exception.WxBizException;
import com.citybiz.common.utils.uuid.UUID;
import com.citybiz.system.service.FileUploadService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.CreateBucketRequest;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Service;


import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.util.Date;

/**
 * create by Ykg on 2023/10/12
 * effect: 腾讯云文件上传实现
 */
@Service(value = "tencentFileUploadServiceImpl")
@Slf4j
public class TencentFileUploadServiceImpl implements FileUploadService {

    @Resource
    private TencentCosConfig tencentCosConfig;

    private COSClient cosClient = null;

    @PostConstruct
    private void initCosClient() {
        String secretId = tencentCosConfig.getSecretId();
        String secretKey = tencentCosConfig.getSecretKey();
        String address = tencentCosConfig.getAddress();
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region cosRegion = new Region(address);
        ClientConfig clientConfig = new ClientConfig(cosRegion);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        cosClient = new COSClient(cred, clientConfig);
    }



    @Override
    public String upload(File file, String suffix) {
        String bucketName = tencentCosConfig.getBucketName();

        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
        createBucketRequest.setCannedAcl(CannedAccessControlList.Private);

        // 指定要上传到 COS 上对象键，即文件名称， 若文件名已存在则会覆盖
        String key = UUID.fastUUID() + suffix;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        try {
            cosClient.putObject(putObjectRequest);
        }catch (Exception e){
            log.error("文件上传失败:{}", JSON.toJSONString(e));
            throw new ServiceException("文件上传失败，请确认");
        }

        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(tencentCosConfig.getBucketName(), key, HttpMethodName.GET);
        Date expiration = new Date(System.currentTimeMillis() + (3600 * 1000 * 24 * 365 * tencentCosConfig.getYear()));
        request.setExpiration(expiration);

        // 返回访问链接
        return cosClient.generatePresignedUrl(request).toString();

    }
}